package com.zpark.sports.controller;

import com.zpark.sports.pojo.BasketballMallUser;
import com.zpark.sports.service.IUserService;
import com.zpark.sports.utils.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 用户控制层
 */
@Controller
@RequestMapping("/user")
@Api(tags = "用户控制层接口")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    /**
     * 注册接口
     * @param user
     * @return
     */
    @PostMapping("/reg")
    @ApiOperation("注册接口")
    @ApiImplicitParam(name = "user", value = "用户对象")
    public ModelAndView reg(BasketballMallUser user){
        // 创建视图解析器对象
        ModelAndView mv = new ModelAndView();
        // 设置视图解析
        mv.setViewName("login");

        // 调用业务层方法执行注册功能
        userService.addUser(user);

        return mv;
    }

    /**
     * 访问注册页面接口
     * @return
     */
    @RequestMapping("/reg_page")
    @ApiOperation("获取用户注册页面接口")
    public ModelAndView regPage(){
        // 创建视图解析器对象
        ModelAndView mv = new ModelAndView();
        // 设置视图解析
        mv.setViewName("register");

        return mv;
    }

    @PostMapping("/user_login")
    @ApiOperation("用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名"),
            @ApiImplicitParam(name = "password", value = "用户密码"),
            @ApiImplicitParam(name = "request", value = "请求对象")
    })
    public ModelAndView login(String username, String password, HttpServletRequest request){
        // 创建视图解析器对象
        ModelAndView mv = new ModelAndView();
        // 设置视图解析
        mv.setViewName("index");

        // 调用业务层方法执行登录
        BasketballMallUser user = userService.userLogin(username, password);

        // 将登录信息保存到session域中
        HttpSession session = request.getSession();
        session.setAttribute("User", user);

        return mv;
    }

    @GetMapping("/user_info")
    @ApiOperation("获取用户登录信息接口")
    @ApiImplicitParam(name = "request", value = "请求对象")
    @ResponseBody
    public JsonResult<BasketballMallUser> getUserInfo(HttpServletRequest request){
        // 获取用户登录信息
        return new JsonResult<BasketballMallUser>(CODE_SUCCESS, null, getUser(request.getSession()));
    }


}
